<template>
  <div style="margin: 12px">
    <el-form :model="queryForm" ref="queryForm" size="small" :inline="true" label-width="68px" class="globalSerchFormStyle">
      <el-row>
        <el-col :span="6" v-if="authUser">
          <el-form-item label="油企名称" prop="enterpriseId">
            <el-select v-model="queryForm.enterpriseId" :clearable="true" filterable placeholder="请选择油企" @change="handleSelectChangeEnterprise" style="width: 190px">
              <el-option v-for="(item, index) in enterpriseList" :key="index" :value="item.enterpriseId" :label="item.enterpriseName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="油站名称" prop="stationId" clearable>
            <el-select v-model="queryForm.stationId" :clearable="true" filterable placeholder="请选择油站" style="width: 190px">
              <el-option v-for="item in stationList" :key="item.stationId" :label="item.stationName" :value="item.stationId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="queryForm.deviceName" placeholder="请输入设备名称" clearable size="small" @keyup.enter.native="handleQuery" style="width: 190px"/>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="!authUser">
          <el-form-item label="设备类型" prop="deviceType">
            <el-select v-model="queryForm.deviceType" clearable placeholder="请选择" size="small" style="width: 190px">
              <el-option label="pos机" value="1"></el-option>
              <el-option label="双屏机" value="2"></el-option>
              <el-option label="小票机" value="3"></el-option>
              <el-option label="云喇叭" value="4"></el-option>
              <el-option label="云音箱" value="8"></el-option>
              <el-option label="继电器" value="9"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 隐藏区 -->
      <el-row v-show="collapse">
        <el-col :span="6" v-if="authUser">
          <el-form-item label="设备类型" prop="deviceType">
            <el-select v-model="queryForm.deviceType" clearable placeholder="请选择" size="small" style="width: 190px">
              <el-option label="pos机" value="1"></el-option>
              <el-option label="双屏机" value="2"></el-option>
              <el-option label="小票机" value="3"></el-option>
              <el-option label="云喇叭" value="4"></el-option>
              <el-option label="云音箱" value="8"></el-option>
              <el-option label="继电器" value="9"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="终端号" prop="deviceNo">
            <el-input v-model="queryForm.deviceNo" placeholder="请输入终端号" clearable size="small" @keyup.enter.native="handleQuery" style="width: 190px"/>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="6">
          <el-form-item label="密钥" prop="deviceSerialNum">
            <el-input
              v-model="queryForm.deviceSerialNum"
              placeholder="请输入设备密钥"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备编号" prop="likeDeviceNo">
            <el-input
              v-model="queryForm.likeDeviceNo"
              placeholder="请输入设备编号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>

    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          class="fcous"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          id="closeSearchBtn"
          @click="
            (closeSearch) => {
              collapse = !collapse;
            }
          "
        >
          {{ collapse ? "收起" : "展开更多" }}
          <i :class="collapse ? 'el-icon-arrow-up ' : 'el-icon-arrow-down'"></i>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDeleteAll"
          :disabled="selection.length < 1"
          >删除</el-button
        >
      </el-col>
    </el-row>
    <el-table
      stripe
      :data="equipmentList"
      @selection-change="handleSelectChange"
    >
      <el-table-column type="selection" width="55" />
      <af-table-column
        label="油企名称"
        align="left"
        prop="enterpriseName"
        v-if="authUser"
      />
      <af-table-column label="油站名称" align="left" prop="stationName" />
      <!--
      <af-table-column
        label="油站名称"
        align="left"
        prop="stationName"
        v-if="jiBie !== 2"
      />
      -->
      <af-table-column label="设备名称" align="left" prop="deviceName" />
      <af-table-column label="设备类型" align="left" prop="deviceType">
        <template slot-scope="scope">
          {{
            scope.row.deviceType == "1"
              ? "POS"
              : "" + scope.row.deviceType == "2"
              ? "双屏机"
              : "" + scope.row.deviceType == "3"
              ? "小票机"
              : scope.row.deviceType === "4"
              ? "云喇叭"
              : "" + scope.row.deviceType == "8"
              ? "云音箱"
              : ""
          }}
        </template>
      </af-table-column>

      <af-table-column label="小票类型" align="left" prop="printType">
        <template slot-scope="scope">
          <span v-if="scope.row.printType == '1'">顾客联</span>
          <span v-else-if="scope.row.printType == '2'">商户联</span>
          <span v-else-if="scope.row.printType == '3'">顾客+商户联</span>
          <span v-else>-</span>
        </template>
      </af-table-column>
      <af-table-column label="终端号" align="left" prop="deviceNo" />

      <af-table-column label="终端密钥" align="left" prop="deviceSerialNum">
        <template slot-scope="scope">
          {{ scope.row.deviceSerialNum ? scope.row.deviceSerialNum : "-" }}
        </template>
      </af-table-column>
      <!--
      <af-table-column label="绑定油枪号" align="left" prop="gunNo" />
      -->
      <af-table-column label="设备厂家" align="left" prop="deviceFactory">
        <template slot-scope="scope">
          <span v-if="scope.row.deviceFactory === '1'">易联云</span>
          <span v-else-if="scope.row.deviceFactory === '2'">飞鹅</span>
          <span v-else-if="scope.row.deviceFactory === '3'">易联云K4</span>
          <span v-else>-</span>
        </template>
      </af-table-column>
      <!-- <af-table-column label="排序" align="left" prop="deviceFactory" /> -->
      <af-table-column label="添加时间" align="left" prop="createTime" />

      <af-table-column
        label="最近一次修改时间"
        align="left"
        prop="updateTime"
      />

      <af-table-column
        label="操作"
        align="left"
        fixed="right"
        class-name="small-padding fixed-width"
        width="200px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </af-table-column>
    </el-table>

    <pagination
      :hidden="total > 0 ? false : true"
      :total="total"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      @pagination="getList"
      :autoScroll="true"
    />

    <!-- 添加或修改油站设备管理对话框 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      size="40%"
      custom-class="add-drawer"
    >
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        :rules="rules"
        label-width="150px"
      >
        <!--
        :rules="{
          required: (form.userLevel==1 || form.userLevel==2),
          message: '请选择油企名称',
          trigger: 'change',
        }"
        :rules="{
          required: form.userLevel==2,
          message: '请选择油企名称',
          trigger: 'change',
        }"
      -->
        <el-form-item label="油企名称" prop="enterpriseId" v-if="authUser">
          <el-select
            v-model="dialogForm.enterpriseId"
            :clearable="true"
            filterable
            placeholder="请选择油企"
            @change="handleSelectChangeEnterpriseForm"
          >
            <el-option
              v-for="(item, index) in enterpriseList"
              :key="index"
              :value="item.enterpriseId"
              :label="item.enterpriseName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="归属站点" prop="stationId" v-if="isEnterprise">
          <el-select
            v-model="dialogForm.stationId"
            @change="changeStationId"
            placeholder="请选择归属站点"
            size="small"
          >
            <el-option
              :label="ele.stationName"
              :value="+ele.stationId"
              v-for="ele in stationListOptions"
              :key="ele.stationId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备类型" prop="deviceType">
          <el-select
            v-model="dialogForm.deviceType"
            placeholder="请选择设备类型"
            clearable
            size="small"
          >
            <el-option label="POS" value="1"></el-option>
            <el-option label="双屏机" value="2"></el-option>
            <el-option label="小票机" value="3"></el-option>
            <el-option label="云喇叭" value="4"></el-option>
            <el-option label="云音箱" value="8"></el-option>
            <el-option label="继电器" value="9"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="设备厂家"
          prop="deviceFactory"
          v-if="dialogForm.deviceType == 3"
        >
          <el-select
            v-model="dialogForm.deviceFactory"
            placeholder="请选择设备厂家"
            clearable
            size="small"
          >
            <el-option label="易联云" value="1"></el-option>
            <el-option label="飞鹅" value="2"></el-option>
            <el-option label="易联云K4" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="打印小票类型"
          prop="printType"
          v-if="['1', '3'].includes(dialogForm.deviceType) "
        >
          <el-select
            v-model="dialogForm.printType"
            placeholder="请选择小票类型"
            clearable
            size="small"
          >
            <el-option label="顾客联" value="1"></el-option>
            <el-option label="商户联" value="2"></el-option>
            <el-option label="顾客+商户联" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="绑定员工或者油枪"v-if="dialogForm.deviceType!=9" >
          <el-radio-group v-model="radioUser" @input="inputRadio">
            <el-radio label="1">员工</el-radio>
            <el-radio label="0">油枪</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-show="radioUser === '1'&&dialogForm.deviceType!=9" prop="userIdList">
          <template v-if="personnelList.length === 0">
            {{ "木有拉取到员工，请先配置员工" }}
          </template>
          <template v-else>
            <el-checkbox-group v-model="dialogForm.userIdList">
              <el-checkbox
                v-for="item in personnelList"
                :key="item.userId"
                :label="'' + item.userId"
              >
                {{ item.nickName + "-" + item.userName }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </el-form-item>

        <el-form-item v-show="radioUser === '0'" prop="userIdList">
          <template v-if="getAllGunByStationIdList.length === 0">
            {{ "木有拉取到油枪，请先配置油枪" }}
          </template>
          <template v-else>
            <el-checkbox-group v-model="gunNoList">
              <el-checkbox
                v-for="item in getAllGunByStationIdList"
                :key="item"
                :label="item"
              >
                {{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </el-form-item>

        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            v-model="dialogForm.deviceName"
            placeholder="请输入设备名称"
            class="w9"
          />
        </el-form-item>

        <el-form-item
          label="应用ID"
          prop="clientId"
          v-if="
            dialogForm.deviceType == 3 &&
            (dialogForm.deviceFactory == 1 || dialogForm.deviceFactory == 3)
          "
        >
          <el-input
            v-model="dialogForm.clientId"
            placeholder="易联云创建自有型应用获取应用ID"
            class="w9"
          />
        </el-form-item>

        <el-form-item
          label="应用密钥"
          prop="clientSecret"
          v-if="
            dialogForm.deviceType == 3 &&
            (dialogForm.deviceFactory == 1 || dialogForm.deviceFactory == 3)
          "
        >
          <el-input
            v-model="dialogForm.clientSecret"
            placeholder="易联云创建自有型应用获取应用秘钥"
            class="w9"
          />
        </el-form-item>

        <el-form-item :label="dialogForm.deviceType==9?'编码号':'终端号'" prop="deviceNo">
          <el-input
            v-model="dialogForm.deviceNo"
            :placeholder="dialogForm.deviceType==9 ?'请输入编码号':'请输入终端号'"
            @input="deviceNoInput"
            :disabled="(dialogForm.deviceType==9&&isDisabled)?true:false"
            class="w9"
          />
        </el-form-item>
        <el-form-item  label="时长" prop="duration" v-if="dialogForm.deviceType==9">
          <el-input  v-model="dialogForm.duration" placeholder="请输入默认时长" class="w9"/>分钟
        </el-form-item>
        <el-form-item
          label="终端密钥"
          prop="deviceSerialNum"
          v-if="
            dialogForm.deviceType == 1 ||
            dialogForm.deviceType == 2 ||
            dialogForm.deviceType == 3
          "
        >
          <el-input
            v-model="dialogForm.deviceSerialNum"
            placeholder="请输入终端密钥"
            class="w9"
          />
        </el-form-item>

        <el-form-item
          label="是否打印小票"
          prop="isPrint"
          v-if="
            dialogForm.deviceType == 3 &&
            (dialogForm.deviceFactory == 1 || dialogForm.deviceFactory == 3)
          "
        >
          <el-radio-group v-model="dialogForm.isPrint">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="自定义语音"
          prop="refuelAudio"
          v-if="dialogForm.deviceType == 4 || dialogForm.deviceType == 8"
        >
          <customTemplateTag
            ref="trumpetRefuelTemplateTags"
            :templateTags="trumpetRefuelTemplateTags"
            title="加油订单:"
            :maxTags="3"
          />
        </el-form-item>
        <el-form-item
          label="自定义语音"
          prop="refuelAudio"
          v-if="
            dialogForm.deviceType == 3 &&
            (dialogForm.deviceFactory == 1 || dialogForm.deviceFactory == 3)
          "
        >
          <customTemplateTag
            ref="refuelTag"
            :templateTags="refuelTemplateTags"
            title="加油订单:"
          />
        </el-form-item>

        <el-form-item
          prop="shoppingAudio"
          v-if="
            dialogForm.deviceType == 3 &&
            (dialogForm.deviceFactory == 1 || dialogForm.deviceFactory == 3)
          "
        >
          <customTemplateTag
            ref="shoppingTag"
            :templateTags="shoppingTemplateTags"
            title="商城订单:"
          />
        </el-form-item>

        <el-form-item
          prop="rechargeAudio"
          v-if="
            dialogForm.deviceType == 3 &&
            (dialogForm.deviceFactory == 1 || dialogForm.deviceFactory == 3)
          "
        >
          <customTemplateTag
            ref="rechargeTag"
            :templateTags="rechargeTemplateTags"
            title="充值订单:"
          />
        </el-form-item>
        <el-form-item
          label="打印联数"
          prop="printNumber"
          v-if="
            dialogForm.deviceType == 3 &&
            (dialogForm.deviceFactory == 1 || dialogForm.deviceFactory == 3)
          "
        >
          <el-input
            v-model="dialogForm.printNumber"
            placeholder="请输入打印联数"
            class="w9"
          />
        </el-form-item>

        <!-- <el-form-item label="绑定油枪号" prop="checkedGunList" required v-if="dialogForm.deviceType == 1">
          <template v-if="allGunList.length === 0">
            请先在油枪管理里配置油枪
          </template>
          <template v-else>
            <el-checkbox-group v-model="dialogForm.checkedGunList" v-if="dialogForm.deviceType == 2">
              <el-checkbox v-for="item in posList" :key="item.oilGunId" :label="item.oilGunNo" :value="item.oilGunNo">
                {{ item.oilGunNo + "号枪/" + item.oilName }}
              </el-checkbox>
            </el-checkbox-group>

            <el-checkbox-group v-model="dialogForm.checkedGunList" v-if="dialogForm.deviceType == 1">
              <el-checkbox v-for="item in printList" :key="item.oilGunId" :label="item.oilGunNo" :value="item.oilGunNo">
                {{ item.oilGunNo + "号枪/" + item.oilName }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </el-form-item> -->
      </el-form>
      <div style="text-align: right; margin-bottom: 20px">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listManage,
  getManage,
  delManage,
  addManage,
  updateManage,
  exportManage,
  changeManageStatus,
  addEquipmentApi,
  editEquipmentApi
} from "@/api/station/manage";
import { enterpriseList } from "@/api/station/orderHistory";
import { listEnterpriseStation } from "@/api/dept";
import { listPersonnel,listPersonnel2, getAllGunByStationId } from "@/api/station/personnel";

import { getEnterpriseList, getStationList } from "@/api/dept";
import customTemplateTag from "@/components/customTemplateTag";

export default {
  name: "Station_Equipment",
  components: { customTemplateTag },
  data() {
    let validateGunNo = (rule, value, callback) => {
      if (this.allGunList.length === 0) {
        callback(new Error("请先配置油枪后再来配置设备"));
        return;
      }
      if (this.dialogForm.checkedGunList.length === 0) {
        callback(new Error("请勾选要绑定的油枪"));
        return;
      }
      callback();
    };
    return {
      // 选择员工或者油枪
      bindingType: "staff",
      gunNoList: [],
      radioUser: "1",
      // 添加油枪列表
      getAllGunByStationIdList: [],

      refuelTemplateTags: ["手机尾号", "加油金额", "支付金额", "枪号", "油品"],
      trumpetRefuelTemplateTags: ["油品名称", "枪号", "应付金额", "实付金额"],
      shoppingTemplateTags: ["手机尾号", "订单总额", "实付金额"],
      rechargeTemplateTags: ["手机尾号", "充值金额", "赠送金额"],
      stationId: null, // 绑定油站员工,
      pageStatus: 0,
      // 油站设备管理表格数据
      equipmentList: [],
      // 油枪复选
      allGunList: [],
      // 已选的油枪
      checkedGunList: [],
      //设备状态
      stationOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 总条数
      total: 100,
      // 查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 10, // 初始值只能比10大
        deviceNo: null,
        deviceSerialNum: null, // 设备密钥
        likeDeviceNo: null,
        stationId: null,
      },
      // 弹窗表单参数
      dialogForm: {},
      currentList: [],
      // 表单校验
      rules: {
        enterpriseId: [
          { required: true, message: "请选择油企", trigger: "change" },
        ],
        stationId: [
          { required: true, message: "请选择归属站点", trigger: "blur" },
        ],
        deviceFactory: [
          { required: true, message: "请输入设备厂家", trigger: "change" },
        ],
        printType: [
          { required: true, message: "请输入小票类型", trigger: "change" },
        ],
        deviceNo: [
          { required: true, message: "请输入设备编号", trigger: "blur" },
        ],
        deviceName: [
          { required: true, message: "请输入设备名称", trigger: "blur" },
          {
            pattern: /^(.{0,22})$/,
            message: "不能超过22个字符",
            trigger: "blur",
          },
        ],
        deviceType: [
          { required: true, message: "请选择设备类型", trigger: "blur" },
        ],
        checkedGunList: [{ validator: validateGunNo, trigger: "change" }],
        clientId: [
          { required: true, message: "请输入应用ID", trigger: "blur" },
        ],
        clientSecret: [
          { required: true, message: "请输入应用密钥", trigger: "blur" },
        ],
        deviceNo: [
          { required: true, message:this.dialogForm&&this.dialogForm.deviceType==9 ? '请输入编码号':"请输入终端号", trigger: "blur" },
        ],
        duration:[
          { required: true, message:"请输入默认时长", trigger: "blur" },
          {
            pattern:/^\d+$/,
            message: "只能输入整数",
            trigger: "blur",
          },
        ],
        deviceSerialNum: [
          { required: true, message: "请输入终端密钥", trigger: "blur" },
        ],
        isPrint: [
          { required: true, message: "请选择是否打印小票", trigger: "change" },
        ],
        //  refuelAudio: [
        //   { required: true, message: "请输入加油订单语音", trigger: "blur" },
        // ],
        // shoppingAudio: [
        //   { required: true, message: "请输入商城订单语音", trigger: "blur" },
        // ],
        // rechargeAudio: [
        //   { required: true, message: "请输入充值订单语音", trigger: "blur" },
        // ],
        printNumber: [
          { required: true, message: "请输入打印联数", trigger: "blur" },
        ],
      },
      updateAble: false,
      deviceTypeAble: false,
      groupListOptions: [],
      stationListOptions: [],
      personnelList: [],
      selection: [],
      enterpriseList: [],
      stationList: [],
      collapse: false,
      isDisabled:false
    };
  },
  created() {
    this.init();
    this.setPageStatus();
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getStationList(this.presentEnterprise.enterpriseId, "search");
    }
    this.getEnterpriseList();
  },
  computed: {
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
    isEnterprise() {
      let userLevel = this.$store.state.user.userLevel;
      if (userLevel === "1") {
        return true;
      } else {
        this.dialogForm.stationId = this.$store.state.user.stationId;
        return false;
      }
    },
    // posList() {
    //   // 排除其他pos已经添加过的
    //   const temp = this.allGunList.filter((item) => {
    //     let flag = false;
    //     this.equipmentList.map((ele) => {
    //       if (ele.deviceType == 2) {
    //         if (ele.gunNo.split(",").includes(item.oilGunNo)) {
    //           flag = true;
    //           return;
    //         }
    //       }
    //     });
    //     return flag;
    //   });
    //   // 查找自己的
    //   const temp2 = this.allGunList.filter((item) => {
    //     let flag = true;
    //     temp.map((ele) => {
    //       if (item.oilGunNo == ele.oilGunNo) {
    //         flag = false;
    //       }
    //     });
    //     return flag;
    //   });
    //   return this.currentList.concat(temp2);
    // },
    // printList() {
    //   const temp = this.allGunList.filter((item) => {
    //     let flag = false;
    //     this.equipmentList.map((ele) => {
    //       if (ele.deviceType == 1) {
    //         if (ele.gunNo.split(",").includes(item.oilGunNo)) {
    //           flag = true;
    //           return;
    //         }
    //       }
    //     });
    //     return flag;
    //   });
    //   const temp2 = this.allGunList.filter((item) => {
    //     let flag = true;
    //     temp.map((ele) => {
    //       if (item.oilGunNo == ele.oilGunNo) {
    //         flag = false;
    //       }
    //     });
    //     return flag;
    //   });
    //   return this.currentList.concat(temp2);
    // },
  },
  methods: {
    // 员工油枪
    inputRadio() {
      if (this.radioUser === "1") {
        // 员工
        this.bindingType = "staff";
        this.gunNoList = [];
      } else {
        //  油枪
        this.bindingType = "gun";
        this.dialogForm.userIdList = [];
      }
    },
    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    // 查询油站
    getStationList(val, key) {
      listEnterpriseStation({ enterpriseId: val }).then((res) => {
        if (res.length === 1) {
          this.getPersonnelList(res[0].stationId);
          this.getAllGunByStationId(res[0].stationId);
        }
        if (key === "search") {
          this.stationList = res;
        } else {
          this.stationListOptions = res;
        }
      });
    },
    // 搜索选择油企
    handleSelectChangeEnterprise(val) {
      this.stationList = [];
      this.queryForm.stationId = null;
      this.getStationList(val, "search");
    },
    async handleSelectChangeEnterpriseForm(val) {
      this.personnelList = [];
      this.stationId = null;
      this.stationListOptions = [];
      this.dialogForm.stationId = null;
      this.getStationList(val);
      await listEnterpriseStation({ enterpriseId: val }).then((res) => {
        this.stationListOptions = res;
      });
      this.stationId =
        this.stationListOptions[0] && this.stationListOptions[0].stationId;
      this.getPersonnelList(this.stationId);
      this.getAllGunByStationId(this.stationId);
    },
    changeStationId(id) {
      this.getPersonnelList(id);
      this.getAllGunByStationId(id);
    },

    // 选择归属站点后获取油枪
    getAllGunByStationId(id) {
      if (id) {
        getAllGunByStationId(id).then((res) => {
          if (res && res.code === 200) {
            this.getAllGunByStationIdList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        });
      } else {
        this.getAllGunByStationIdList = [];
      }
    },

    getPersonnelList(id) {
      listPersonnel2({
        // enterpriseId: this.presentEnterprise ? this.presentEnterprise.enterpriseId : '',
        stationId: id,
        userLevel: "2",
      }).then((response) => {
        this.personnelList = response.rows;
      });
    },
    // getStationList() {
    //   getStationList({
    //     pageSize: 10000,
    //     pageNum: 1,
    //     enterpriseId: this.presentEnterprise.enterpriseId
    //   })
    //     .then((res) => {
    //       this.stationListOptions = res.rows;
    //     }).catch((err) => { })
    // },
    init() {
      this.getList();
    },
    setPageStatus() {
      this.queryPageStatus([2]).then((res) => {
        this.pageStatus = res;
      });
    },
    /** 查询油站设备管理列表 首页表单 */
    getList() {
      listManage(this.queryForm).then((response) => {
        this.equipmentList = response.rows;
        this.total = response.total;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getList();
    },
    deviceNoInput(value) {
      this.dialogForm.posQueue = value;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.bindingType = "staff";
      this.radioUser = "1";
      this.personnelList = [];
      this.dialogForm.userIdList = [];
      this.getAllGunByStationIdList = [];
      this.gunNoList = [];
      this.isDisabled=false
      if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
        this.getStationList(this.presentEnterprise.enterpriseId);
      }
      this.updateAble = false;
      this.currentList = [];
      this.title = "添加油站设备管理";
      this.dialogForm = {
        checkedGunList: [],
        deviceType: null,
        enterpriseId: "",
        stationId: "",
        posFanoutExchange: "posFanoutExchange-" + this.deptId,
        userIdList: [],
        printNumber: 1,
        isPrint: 1,
      };
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isDisabled=true
      if (row.bindingType === "gun") {
        this.radioUser = "0";
        this.bindingType = "gun";
        this.gunNoList = row.gunNo.split(",");
      } else if (row.bindingType === "staff") {
        this.gunNoList = [];
        this.radioUser = "1";
        this.bindingType = "staff";
      }
      this.getEnterpriseList();
      this.getStationList(row.enterpriseId);
      this.getPersonnelList(row.stationId);
      this.getAllGunByStationId(row.stationId);
      // 查找自己已经选中的枪号
      this.updateAble = true;
      this.currentList = this.allGunList.filter((ele) => {
        return row.gunNo.split(",").includes(ele.oilGunNo);
      });
      let checkedGunList;
      // 将自己有的抢号 默认勾选
      if (Object.prototype.toString.call(row.gunNo) === "[object String]") {
        checkedGunList = [...new Set(row.gunNo.split(","))].filter((ele) => {
          return ele.toString().trim() !== "";
        });
      } else {
        checkedGunList = [];
      }
      if (!row.userIdList) {
        row.userIdList = [];
      }

      row.enterpriseId = parseInt(row.enterpriseId);
      this.dialogForm = { ...row, checkedGunList };

      this.title = "修改油站设备管理";
      this.open = true;
      this.$nextTick(() => {
        // 字符串;被分隔会变成 两个字符串，需要排除干扰
        if (row.audio && row.audio !== ";") {
          // let list = row.audio.split(";");
          let list = row.audio.replace(/;+/g, ";").split(";"); // 使用正则表达式替换连续的分隔符
          if (this.$refs.trumpetRefuelTemplateTags) {
            this.$refs.trumpetRefuelTemplateTags.tags = list[0]
              .split(",")
              .filter(Boolean);
          } else {
            this.$refs.refuelTag.tags = list[0].split(",").filter(Boolean); //过滤数组里面的空值
            this.$refs.shoppingTag.tags = list[1].split(",").filter(Boolean);
            this.$refs.rechargeTag.tags = list[2].split(",").filter(Boolean);
          }
        }
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          if(this.dialogForm.deviceType==9){ 
            let minutes=Number(this.dialogForm.duration*60).toString(16).padStart(2, '0')
            if(minutes.length>2){ 
              minutes=this.transformNumber(minutes)
            }else{ 
              minutes=minutes+'000000000'
            }
            const params={
              deviceId:this.dialogForm.deviceId,
              deviceName:this.dialogForm.deviceName,
              deviceNo:this.dialogForm.deviceNo,
              deviceType:this.dialogForm.deviceType,
              stationId:this.dialogForm.stationId,
              duration:Number(this.dialogForm.duration),
              durationConversion:`550c00FF010001${minutes}`
            } 
            if(this.dialogForm.deviceId){ 
              editEquipmentApi(params).then((res)=>{
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
            }else{ 
              delete params['deviceId']
              addEquipmentApi(params).then((res)=>{
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
            }
          }else{ 
            let list = [];
            for (let i = 0; i < this.dialogForm.checkedGunList.length; i++) {
              for (let j = 0; j < this.allGunList.length; j++) {
                if (
                  this.dialogForm.checkedGunList[i] == this.allGunList[j].oilGunNo
                ) {
                  list.push(this.allGunList[j].oilGunNo);
                }
              }
            }
            this.dialogForm.gunNo = list.toString();
            if (
              (this.$refs.refuelTag && this.dialogForm.deviceType !== "4") ||
              (this.$refs.refuelTag && this.dialogForm.deviceType !== "8")
            ) {
              let refuelTag = this.$refs.refuelTag.getTags();
              let shoppingTag = this.$refs.shoppingTag.getTags();
              let rechargeTag = this.$refs.rechargeTag.getTags();
              this.dialogForm.audio = `${refuelTag.join(",")};${shoppingTag.join(
                ","
              )};${rechargeTag.join(",")}`;
            }
            // 云喇叭判断
            if (
              (this.$refs.trumpetRefuelTemplateTags &&
                this.dialogForm.deviceType == "4") ||
              (this.$refs.trumpetRefuelTemplateTags &&
                this.dialogForm.deviceType == "8")
            ) {
              let trumpetRefuelTemplateTags =
                this.$refs.trumpetRefuelTemplateTags.getTags();
              this.dialogForm.audio = `${trumpetRefuelTemplateTags.join(",")};`;
            }
              const gunNoList = this.gunNoList.join(",");
            if (this.dialogForm.deviceId != null) {
              this.dialogForm.userIds = this.dialogForm.userIdList.join(",");
              updateManage({
                ...this.dialogForm,
                gunNo: gunNoList,
                bindingType: this.bindingType,
              }).then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addManage({
                ...this.dialogForm,
                gunNo: gunNoList,
                bindingType: this.bindingType,
              }).then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
          //this.dialogForm.gunNo = this.dialogForm.checkedGunList.toString();
        } else {
          console.log("失败");
        }
      });
    },
    transformNumber(num) {
      // 将数字转换成字符串
      let numStr = num.toString();
        // 获取最后两位数字
      let lastTwoDigits = numStr.slice(-2);
      
      // 移除最后两位数字
      let numWithoutLastTwoDigits = numStr.slice(0, -2);
      
      // 将最后两位数字放到字符串开头
      let result = lastTwoDigits + numWithoutLastTwoDigits;
      if(result.length==3){ 
       const numWithoutLastDigit = result.slice(-1);
       const numWithoutLastDigit2 = result.slice(0,-1);
       result=numWithoutLastDigit2+'0'+numWithoutLastDigit
      }
      // 如果不满12位，补0
      while (result.length < 12) {
          result =result+'0';
      }
      return result
    },
    handleSelectChange(selection) {
      this.selection = selection;
    },
    handleDeleteAll() {
      let deviceIds = [];
      this.selection.forEach((item) => {
        deviceIds.push(item.deviceId);
      });
      this.$confirm("是否确认删除油站设备管理", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delManage(deviceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let deviceIds = [];
      deviceIds.push(row.deviceId);
      this.$confirm("是否确认删除油站设备管理", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delManage(deviceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    comDeviceType(val) {
      // 每个油站只能有一种设备，以第一次添加的设备为准
      if (this.equipmentList.length == 0) {
        this.deviceTypeAble = false;
        return true;
      }
      this.dialogForm.deviceType = this.equipmentList[0].deviceType;
      this.deviceTypeAble = true;
      return this.equipmentList[0].deviceType == val;
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   const queryForm = this.queryForm;
    //   this.$confirm("是否确认导出所有油站设备管理数据项?", "警告", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(function () {
    //       return exportManage(queryForm);
    //     })
    //     .then((response) => {
    //       this.download(response.msg);
    //     });
    // },
  },
};
</script>
<style>
.add-drawer {
  overflow-y: auto;
  padding: 0 10px;
}

.w9 {
  width: 90%;
}

.custom-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 90%;
  display: inline-block;
}
</style>
